package com.forest.core.widget.dialog

import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentManager

/**
 *    author : duanguosen
 *    date   : 2019/12/3
 *    desc   :
 */
class FDialog : FBaseDialog(), FDialogInterface {

    companion object {

        fun newInstance(): FDialog {
            return FDialog()
        }
    }

    private var mOnBuilderViewListener: FDialogInterface.OnBuilderViewListener? = null

    private var mOnDismissListener: FDialogInterface.OnDismissListener? = null

    override fun dismiss() {
        activity?.run {
            if (!isFinishing && !isDetached) {
                dismissAllowingStateLoss()
            }
        }
    }

    fun setOnBuilderViewListener(onBuilderViewListener: FDialogInterface.OnBuilderViewListener) {
        mOnBuilderViewListener = onBuilderViewListener
    }

    fun setOnDismissListener(onDismissListener: FDialogInterface.OnDismissListener) {
        mOnDismissListener = onDismissListener
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        getRootView()?.let {
            mOnBuilderViewListener?.onBuilderView(this, it, options.layoutRes)
        }
    }

    override fun onDestroy() {
        mOnDismissListener?.onDismiss(this)
        super.onDestroy()
    }

//    private fun showAllowingLoss(manager: FragmentManager, tag: String?) {
//        try {
//            val mDismissed = this.javaClass.superclass.getDeclaredField("mDismissed")
//            val mShownByMe = this.javaClass.superclass.getDeclaredField("mShownByMe")
//            mDismissed.isAccessible = true
//            mShownByMe.isAccessible = true
//            mDismissed.setBoolean(this, false)
//            mShownByMe.setBoolean(this, true)
//        } catch (e: NoSuchFieldException) {
//            e.printStackTrace()
//        } catch (e: IllegalAccessException) {
//            e.printStackTrace()
//        }
//        this.isCancelable = options.isCancelable
//        val ft = manager.beginTransaction()
//        ft.add(this, tag)
//        // 这里把原来的commit()方法换成了commitAllowingStateLoss()
//        ft.commitAllowingStateLoss()
//    }
//
//    override fun show(manager: FragmentManager, tag: String?) {
//        showAllowingLoss(manager, tag)
//    }

}